import time

import utime
import random
from neopixel import NeoPixel
from machine import Pin
from 驱动.ws2812Screen import WS2812Screen
from 驱动.debounce import *
from setting import *
from wifi_getinfo import *
from 驱动.mpu6050 import accel
import random
from machine import SoftI2C
import micropython
from ImgData import *

from machine import Timer

class Pixel:
    def __init__(self):
        self.np = NeoPixel(Pin(LED_PIN), num_leds + 64)  # 创建像素序列对象
        self.screen = WS2812Screen(self.np, SCREEN_WIDTH, SCREEN_HEIGHT)  # 创建屏幕对象
        self.bright = 0.5
        self.menu_index = 0
        self._menu_index_MAX = 5
        self.all_info = {'stars': 7228, 'coins': 2345, 'now_stock': 3214.41, 'fans': 597334, 'likes': 9952,
                         'yes_stock': 3213.59}
        self.button_L = Debounce(BUTTON_L_PIN)  # L键  默认消抖10ms，默认上拉
        self.button_OK = Debounce(BUTTON_OK_PIN)
        self.button_C = Debounce(BUTTON_C_PIN)
        self.button_R = Debounce(BUTTON_R_PIN)
        #self.buzzer = Pin(19, Pin.OUT, value=0)
        #self.mic = Pin(23)
        self.buzzer = Pin(BUZZER_PIN, Pin.OUT, value=0)
        self.mic = Pin(MIC_PIN)
        self.i2c = SoftI2C(sda=Pin(sda_Pin), scl=Pin(scl_Pin), freq=40000)

        # 第二个参数为加速度最大量程
        # 0 ±2G   1  ±4G
        # 2 ±8G   3  ±16G
        self.mpu = accel(self.i2c, 0)
      
        self.tim1 = Timer(1)
    

    def turn_on_show(self):
        """开机动画"""
        wifi_connect_x = [24, 26, 28]

        # 先显示流水灯
        for i in range(8):
            for j in range(32):
                self.screen.draw_pixel(j, i, (50, 10 + j * 5, 10 + i * 10), 0.5)
                self.screen.show()
        self.screen.fill_screen()  # 清屏
        time.sleep(0.5)

        # 然后显示WiFi连接的画面
        self.screen.draw_img(0, 0, wifi22x8[0], self.bright)
        self.screen.show()
        time.sleep(1)
        #  有的板子连接wifi后会导致led乱闪，可尝试把wifi功能运行在另一个核上
        while not wifi_connect():
            for x in range(len(wifi_connect_x)):
                self.screen.draw_pixel(x, 6, [76, 175, 80], self.bright)
                self.screen.show()
                time.sleep(0.5)
            for x in range(len(wifi_connect_x)):
                self.screen.draw_pixel(x, 6, [0, 0, 0], self.bright)
                self.screen.show()

        # 清除连接中的三个点，然后显示√表示连接成功
        for x in range(len(wifi_connect_x)):
            self.screen.draw_pixel(x, 6, [0, 0, 0], self.bright)
            self.screen.show()
        self.screen.draw_img(23, 0, wifi22x8[1], self.bright)
        self.screen.show()
        time.sleep(1)

    def menu(self):
        while True:
            self.screen.draw_img(0, 0, menu32x8[self.menu_index], 0.3)
            self.screen.show()
            if self.button_L.is_pressed():
                self.menu_index -= 1
                if self.menu_index < 0:
                    self.menu_index = self._menu_index_MAX
            if self.button_R.is_pressed():
                self.menu_index += 1
                if self.menu_index > self._menu_index_MAX:
                    self.menu_index = 0

            if self.button_OK.is_pressed():  # 0 time, 1 bilibili, 2 info, 3 game, 4 gif, 5 set
                # 0 time
                if self.menu_index == 0:
                    time_index = 0
                    while True:
                        self.screen.fill_screen()
                        self.screen.draw_img(12, 0, time_menu11x8[time_index])
                        self.screen.show()
                        if self.button_L.is_pressed():
                            time_index -= 1
                            if time_index < 0:
                                time_index = 1
                        if self.button_R.is_pressed():
                            time_index += 1
                            if time_index > 1:
                                time_index = 0
                        if self.button_OK.is_pressed():
                            if time_index == 0:  # 时钟
                                self.time()
                            elif time_index == 1:  # 计时闹钟
                                self.clock()
                        if self.button_C.is_pressed():
                            break  #

                # 1 bilibili
                elif self.menu_index == 1:
                    # TODO 设置定时器获取信息
                    bilibili_index = 0
                    self.tim1.init(period=api_call_freq, mode=Timer.PERIODIC, callback=self.apiCall)
                    while True:
                        self.screen.fill_screen()
                        self.screen.draw_img(12, 0, bilibili9x8[bilibili_index])
                        self.screen.show()
                        if self.button_L.is_pressed():
                            bilibili_index -= 1
                            if bilibili_index < 0:
                                bilibili_index = 3
                        if self.button_R.is_pressed():
                            bilibili_index += 1
                            if bilibili_index > 3:
                                bilibili_index = 0
                        if self.button_OK.is_pressed():
                            if bilibili_index == 0:  # 电视，粉丝数
                                print("start to fans：")
                                self.screen.fill_screen()
                                while True:
                                    #self.screen.draw_num(5, 2, 5, [0, 183, 239], self.bright)
                                    #self.screen.draw_num(9, 2, 9, [0, 183, 239], self.bright)
                                    #self.screen.draw_num(13, 2, 7, [0, 183, 239], self.bright)
                                    #self.screen.draw_num(17, 2, 3, [0, 183, 239], self.bright)
                                    #self.screen.draw_num(21, 2, 3, [0, 183, 239], self.bright)
                                    #self.screen.draw_num(25, 2, 4, [0, 183, 239], self.bright)
                                    self.drawNumber(self.all_info['fans'], [0, 183, 239], self.bright)
                                    self.screen.show()
                                    time.sleep(0.01)
                                    if self.button_C.is_pressed():
                                        break
                            elif bilibili_index == 1:  # 点赞
                                print("likes：")
                                self.screen.fill_screen()
                                while True:
                                    self.screen.draw_num(13, 2, 7, [0, 183, 239], self.bright)
                                    self.screen.draw_num(17, 2, 8, [0, 183, 239], self.bright)
                                    self.screen.draw_num(21, 2, 9, [0, 183, 239], self.bright)
                                    self.screen.draw_num(25, 2, 1, [0, 183, 239], self.bright)
                                    self.screen.show()
                                    time.sleep(0.01)
                                    if self.button_C.is_pressed():
                                        break
                            elif bilibili_index == 2:  # 硬币
                                print("coins：")
                                self.screen.fill_screen()
                                while True:
                                    self.screen.draw_num(13, 2, 2, [0, 183, 239], self.bright)
                                    self.screen.draw_num(17, 2, 0, [0, 183, 239], self.bright)
                                    self.screen.draw_num(21, 2, 3, [0, 183, 239], self.bright)
                                    self.screen.draw_num(25, 2, 1, [0, 183, 239], self.bright)
                                    self.screen.show()
                                    time.sleep(0.01)
                                    if self.button_C.is_pressed():
                                        break
                            elif bilibili_index == 3:  # 收藏
                                print("stars：")
                                self.screen.fill_screen()
                                while True:
                                    self.screen.draw_num(13, 2, 1, [0, 183, 239], self.bright)
                                    self.screen.draw_num(17, 2, 5, [0, 183, 239], self.bright)
                                    self.screen.draw_num(21, 2, 7, [0, 183, 239], self.bright)
                                    self.screen.draw_num(25, 2, 9, [0, 183, 239], self.bright)
                                    self.screen.show()
                                    time.sleep(0.01)
                                    if self.button_C.is_pressed():
                                        break
                        if self.button_C.is_pressed():
                            # TODO 关闭这个定时器
                            self.tim1.deinit()
                            print("定时器关闭")
                            break

                # 2 info
                elif self.menu_index == 2:
                    info_index = 0
                    while True:
                        self.screen.fill_screen()
                        self.screen.draw_img(12, 0, info8x8[info_index])
                        self.screen.show()
                        if self.button_L.is_pressed():
                            info_index -= 1
                            if info_index < 0:
                                info_index = 1
                        if self.button_R.is_pressed():
                            info_index += 1
                            if info_index > 1:
                                info_index = 0
                        if self.button_OK.is_pressed():
                            if info_index == 0:  # 天气
                                print("天气：")
                                self.screen.fill_screen()
                                while True:
                                    self.screen.draw_img(1, 0, info8x8[2], self.bright)
                                    self.screen.draw_num(11, 2, 3, (200, 10, 0), self.bright)
                                    self.screen.draw_num(15, 2, 2, (200, 10, 0), self.bright)
                                    self.screen.draw_pixel(19, 6, (200, 10, 0), self.bright)
                                    self.screen.draw_num(21, 2, 5, (200, 10, 0), self.bright)
                                    self.screen.draw_img(24, 1, info8x8[3], self.bright)
                                    self.screen.show()
                                    time.sleep_ms(10)
                                    if self.button_C.is_pressed():
                                        break
                            elif info_index == 1:  # 股市
                                print("股市：")
                                self.screen.fill_screen()
                                while True:
                                    self.screen.draw_num(3, 2, 3, (200, 10, 0), self.bright)
                                    self.screen.draw_num(7, 2, 2, (200, 10, 0), self.bright)
                                    self.screen.draw_num(11, 2, 1, (200, 10, 0), self.bright)
                                    self.screen.draw_num(15, 2, 3, (200, 10, 0), self.bright)
                                    self.screen.draw_pixel(19, 6, (200, 10, 0), self.bright)
                                    self.screen.draw_num(21, 2, 5, (200, 10, 0), self.bright)
                                    self.screen.draw_num(25, 2, 9, (200, 10, 0), self.bright)
                                    self.screen.show()
                                    time.sleep_ms(10)
                                    if self.button_C.is_pressed():
                                        break
                        if self.button_C.is_pressed():
                            # TODO 关闭这个定时器
                            break

                # 3 game
                elif self.menu_index == 3:
                    game_index = 0
                    while True:
                        self.screen.fill_screen()
                        self.screen.draw_img(0, 0, game32x8[game_index])
                        self.screen.show()
                        if self.button_L.is_pressed():
                            game_index -= 1
                            if game_index < 0:
                                game_index = 1
                        if self.button_R.is_pressed():
                            game_index += 1
                            if game_index > 1:
                                game_index = 0
                        if self.button_OK.is_pressed():
                            if game_index == 0:  # 贪吃蛇
                                print("天气：")
                                self.game()

                            elif game_index == 1:  # 俄罗斯方块
                                print("俄罗斯方块：")
                        if self.button_C.is_pressed():
                            break

                # 4 gif
                elif self.menu_index == 4:
                    self.gif()

                # 5 music
                elif self.menu_index == 5:
                    self.music()

            utime.sleep(0.01)

    # time->时钟
    def time(self):
        print("time")
        time_rgb = [124, 77, 255]
        while True:
            self.screen.fill_screen()  # 填充屏幕，默认黑色，即清屏
            now_time = time.localtime()

            self.screen.draw_num(2, 2, now_time[3] // 10, time_rgb, self.bright)
            self.screen.draw_num(6, 2, now_time[3] % 10, time_rgb, self.bright)
            self.screen.draw_pixel(10, 3, [124, 77, 255], self.bright)
            self.screen.draw_pixel(10, 5, [124, 77, 255], self.bright)

            self.screen.draw_num(13, 2, now_time[4] // 10, time_rgb, self.bright)
            self.screen.draw_num(17, 2, now_time[4] % 10, time_rgb, self.bright)
            self.screen.draw_pixel(21, 3, [124, 77, 255], self.bright)
            self.screen.draw_pixel(21, 5, [124, 77, 255], self.bright)

            self.screen.draw_num(24, 2, now_time[5] // 10, time_rgb, self.bright)
            self.screen.draw_num(28, 2, now_time[5] % 10, time_rgb, self.bright)

            if self.button_C.is_pressed():
                return
            self.screen.show()
            time.sleep(0.1)

    # time->定时闹钟
    def clock(self):
        time_rgb = [124, 77, 255]
        clock_rgb = [199, 21, 133]
        clock_red_rgb = [200, 30, 30]

        clock_hour = 0
        clock_min = 0
        clock_sec = 0

        # 设置倒计时的时间
        while True:
            self.screen.fill_screen()  # 填充屏幕，默认黑色，即清屏

            self.screen.draw_num(2, 2, clock_hour // 10, time_rgb, self.bright)
            self.screen.draw_num(6, 2, clock_hour % 10, time_rgb, self.bright)
            self.screen.draw_pixel(10, 3, [124, 77, 255], self.bright)
            self.screen.draw_pixel(10, 5, [124, 77, 255], self.bright)

            self.screen.draw_num(13, 2, clock_min // 10, time_rgb, self.bright)
            self.screen.draw_num(17, 2, clock_min % 10, time_rgb, self.bright)
            self.screen.draw_pixel(21, 3, [124, 77, 255], self.bright)
            self.screen.draw_pixel(21, 5, [124, 77, 255], self.bright)

            self.screen.draw_num(24, 2, 0 // 10, time_rgb, self.bright)
            self.screen.draw_num(28, 2, 0 % 10, time_rgb, self.bright)

            if self.button_R.is_pressed():
                clock_min += 1
                if clock_min > 59:
                    clock_min = 0
                    clock_hour += 1

            if self.button_L.is_pressed():
                clock_min -= 1
                if clock_min < 0 and clock_hour == 0:
                    clock_min = 0
                if clock_min < 0 and clock_hour > 0:
                    clock_min = 59
                    clock_hour -= 1
            if self.button_OK.is_pressed():
                break
            if self.button_C.is_pressed():
                return 
            self.screen.show()
            time.sleep(0.005)

        star_time = time.ticks_ms()

        # 开始倒计时
        while True:
            if time.ticks_diff(time.ticks_ms(), star_time) > 1000:
                star_time = time.ticks_ms()
                clock_sec -= 1

                if clock_sec < 0 and (clock_min > 0 or clock_hour > 0):
                    clock_sec = 59
                    clock_min -= 1
                    if clock_min < 0:
                        clock_min = 59
                        clock_hour -= 1

            self.screen.fill_screen()  # 填充屏幕，默认黑色，即清屏

            self.screen.draw_num(2, 2, clock_hour // 10, clock_rgb, self.bright)
            self.screen.draw_num(6, 2, clock_hour % 10, clock_rgb, self.bright)
            self.screen.draw_pixel(10, 3, clock_rgb, self.bright)
            self.screen.draw_pixel(10, 5, clock_rgb, self.bright)
            self.screen.draw_num(13, 2, clock_min // 10, clock_rgb, self.bright)
            self.screen.draw_num(17, 2, clock_min % 10, clock_rgb, self.bright)
            self.screen.draw_pixel(21, 3, clock_rgb, self.bright)
            self.screen.draw_pixel(21, 5, clock_rgb, self.bright)
            self.screen.draw_num(24, 2, clock_sec // 10, clock_rgb, self.bright)
            self.screen.draw_num(28, 2, clock_sec % 10, clock_rgb, self.bright)

            if self.button_C.is_pressed():
                break
            self.screen.show()
            time.sleep(0.005)

            # 时间到了，时间归零
            if clock_sec < 0 and clock_min == 0 and clock_hour == 0:
                self.screen.fill_screen()  # 填充屏幕，默认黑色，即清屏
                # 蜂鸣器响
                while True:
                    self.buzzer.value(1)
                    self.screen.draw_num(2, 2, clock_hour // 10, clock_red_rgb, self.bright)
                    self.screen.draw_num(6, 2, clock_hour % 10, clock_red_rgb, self.bright)
                    self.screen.draw_pixel(10, 3, clock_rgb, self.bright)
                    self.screen.draw_pixel(10, 5, clock_rgb, self.bright)
                    self.screen.draw_num(13, 2, clock_min // 10, clock_red_rgb, self.bright)
                    self.screen.draw_num(17, 2, clock_min % 10, clock_red_rgb, self.bright)
                    self.screen.draw_pixel(21, 3, clock_rgb, self.bright)
                    self.screen.draw_pixel(21, 5, clock_rgb, self.bright)
                    self.screen.draw_num(24, 2, 0, clock_red_rgb, self.bright)
                    self.screen.draw_num(28, 2, 0, clock_red_rgb, self.bright)
                    self.screen.show()

                    time.sleep(0.2)
                    self.buzzer.value(0)
                    self.screen.draw_num(2, 2, clock_hour // 10, clock_rgb, self.bright)
                    self.screen.draw_num(6, 2, clock_hour % 10, clock_rgb, self.bright)
                    self.screen.draw_pixel(10, 3, clock_rgb, self.bright)
                    self.screen.draw_pixel(10, 5, clock_rgb, self.bright)
                    self.screen.draw_num(13, 2, clock_min // 10, clock_rgb, self.bright)
                    self.screen.draw_num(17, 2, clock_min % 10, clock_rgb, self.bright)
                    self.screen.draw_pixel(21, 3, clock_rgb, self.bright)
                    self.screen.draw_pixel(21, 5, clock_rgb, self.bright)
                    self.screen.draw_num(24, 2, 0, clock_rgb, self.bright)
                    self.screen.draw_num(28, 2, 0, clock_rgb, self.bright)
                    self.screen.show()
                    time.sleep(0.2)
                    if self.button_C.is_pressed():
                        return 

    def game(self):
        print("game")

        # 定义方向和角度的阈值
        THRESHOLD_ANGLE = 0.4

        # 定义贪吃蛇和食物的颜色
        SNAKE_COLOR = (0, 200, 0)  # 红色
        FOOD_COLOR = (200, 0, 0)  # 绿色

        # 初始化贪吃蛇的位置和初始长度
        snake = [(16, 4), (15, 4), (14, 4)]
        snake_length = 3

        # 初始化食物的位置
        food = (random.randint(0, SCREEN_WIDTH - 1), random.randint(0, SCREEN_HEIGHT - 1))

        # 定义贪吃蛇移动的方向
        direction = "RIGHT"

        while True:
            # 读取传感器数据
            accel_data = self.mpu.get_values()
            accel_x = round(accel_data['AcX'] / 16384.0, 2)
            accel_y = round(accel_data['AcY'] / 16384.0, 2)

            # 清空屏幕
            self.screen.fill_screen()

            # 绘制贪吃蛇
            for segment in snake:
                self.screen.draw_pixel(segment[0], segment[1], SNAKE_COLOR)

            # 绘制食物
            self.screen.draw_pixel(food[0], food[1], FOOD_COLOR)

            # 刷新屏幕
            self.screen.show()

            # 等待一段时间
            # 可以根据需要调整游戏速度
            utime.sleep(0.15)

            # 检测按键输入
            # 可以根据具体的硬件平台和引脚配置进行调整
            # if button_OK.is_pressed() and direction != "DOWN":
            #     direction = "UP"
            # elif button_C.is_pressed() and direction != "UP":
            #     direction = "DOWN"
            # elif button_L.is_pressed() and direction != "RIGHT":
            #     direction = "LEFT"
            # elif button_R.is_pressed() and direction != "LEFT":
            #     direction = "RIGHT"

            # 根据传感器数据确定蛇的移动方向
            if abs(accel_x) > THRESHOLD_ANGLE:
                if accel_x > 0 and direction != "LEFT":
                    direction = "RIGHT"
                elif accel_x < 0 and direction != "RIGHT":
                    direction = "LEFT"
            elif abs(accel_y) > THRESHOLD_ANGLE:
                if accel_y > 0 and direction != "UP":
                    direction = "DOWN"
                elif accel_y < 0 and direction != "DOWN":
                    direction = "UP"

            # 根据方向移动贪吃蛇的头部
            head = snake[0]
            if direction == "UP":
                new_head = (head[0], head[1] - 1)
            elif direction == "DOWN":
                new_head = (head[0], head[1] + 1)
            elif direction == "LEFT":
                new_head = (head[0] - 1, head[1])
            elif direction == "RIGHT":
                new_head = (head[0] + 1, head[1])

            # 检查是否撞到边界或自身
            if new_head[0] < 0 or new_head[0] >= SCREEN_WIDTH or new_head[1] < 0 or new_head[
                1] >= SCREEN_HEIGHT or new_head in snake:
                # 游戏结束
                print("GAME OVER")
                self.screen.fill_screen()
                self.screen.draw_img(0, 0, game32x8[2])
                self.screen.show()
                time.sleep(2)
                break

            # 将新头部加入贪吃蛇
            snake.insert(0, new_head)

            # 检查是否吃到食物
            if new_head == food:
                # 生成新的食物位置
                food = (random.randint(0, SCREEN_WIDTH - 1), random.randint(0, SCREEN_HEIGHT - 1))
                # 增加贪吃蛇的长度
                snake_length += 1

            # 如果贪吃蛇长度超过了指定值，删除尾部
            if len(snake) > snake_length:
                snake.pop()

    def gif(self):
        print("gif")

        # 创建随机雨滴
        def create_raindrop():
            x = random.randint(0, SCREEN_WIDTH - 1)
            speed = random.randint(1, 3)

            r = random.randint(0, 255)
            g = random.randint(0, 255)
            b = random.randint(0, 255)
            color = (r, g, b)
            return (x, 0, speed, color)

        # 代码雨主逻辑
        def code_rain():
            self.screen.fill_screen()
            self.screen.show()

            raindrops = []

            while True:
                self.screen.fill_screen()
                # 创建新雨滴
                if len(raindrops) < 10:
                    raindrops.append(create_raindrop())

                # 更新和绘制雨滴
                for i in range(len(raindrops)):
                    x, y, speed, color = raindrops[i]

                    # 绘制当前雨滴
                    self.screen.draw_pixel(x, y, color)

                    # 更新当前雨滴位置
                    y += 1

                    # 边界处理
                    if y >= SCREEN_HEIGHT:
                        raindrops[i] = create_raindrop()
                    else:
                        raindrops[i] = (x, y, speed, color)

                    # 控制雨滴下落速度
                    time.sleep(0.005)
                self.screen.show()
                if self.button_C.is_pressed():
                    return

        code_rain()

    def music(self):
        self.screen.fill_screen()
        self.screen.show()
        time.sleep(2)
        while True:
            self.screen.fill_screen()
            #     if mic.value() == 0:
            #         print("有声音")
            for x in range(SCREEN_WIDTH):
                r = random.randint(0, 255)
                g = random.randint(0, 255)
                b = random.randint(0, 255)
                color = (r, g, b)
                for y in range(random.randint(1, 7)):
                    self.screen.draw_pixel(x, 7 - y, color)
            time.sleep_ms(100)
            self.screen.show()
            if self.button_C.is_pressed():
                return
    def apiCall(self, time):
         print("APIcalled")
         res=get_info()
         print(res)
         self.all_info = res
    def drawNumber(self, number, color, bright):
         print("draw Number " , number)
         x = 5
         char1 = str(number)
         for item in [c for c in char1]:
            print(item)
            self.screen.draw_num(x, 2, item, color, bright)
            x = x + 4
         
